package MianCalPak;

import java.io.IOException;
import java.sql.ResultSet;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DB.DBProvider;


/**
 * Servlet implementation class Registration
 */
public class Registration extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Registration() {
        super();
        // TODO Auto-generated constructor stub
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 doPost(request, response);
		 return;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//get parameters from registration form
		
		String user = request.getParameter("username");
		String pass = request.getParameter("password");
		String firstName = request.getParameter("first_name");
		String lastName = request.getParameter("last_name");
		String phone = request.getParameter("number");
		String admin = request.getParameter("choice");
		String code = request.getParameter("code");
		
		//Check input - server side!
		
		if (null == pass || 
			null == user || 
			null == firstName ||
			null == lastName ||
			pass.length() > 8 || 
			user.length() > 8 ||
			firstName.length() > 15 ||
			lastName.length() > 15 ||
			phone.length() > 15 ||
			!(phone.matches("[0-9]+"))){
			
				response.sendError(HttpServletResponse.SC_BAD_REQUEST);
				return;
			}
			
			Properties p = new Properties();
			p.load(getServletContext().getResourceAsStream("/WEB-INF/config"));
			
			
			//admin account 
			if (admin.equals("yes")){
				if (!p.getProperty("adminCode").equals(code)){
					request.getSession().setAttribute("wrongCode", "yes");
					response.sendRedirect("index.jsp");
					return;
				}
			}
			
			try {
				
				DBProvider provider = new DBProvider(p);
				
				//check if username exist
				ResultSet res = (new DBProvider(p)).userDetails(user);
				
				if (res.next()){
					request.getSession().setAttribute("usernameExist", "yes");
					response.sendRedirect("index.jsp");
					return;
				} 
				
				//register user
				provider.registerUser(user, pass, firstName, lastName, phone, (admin.equals("yes")));
			
				//goto login
				response.sendRedirect("index.jsp");
			}		
			
			catch (Exception e) {
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				e.printStackTrace();} 
	}
	
}
